/*
 * @Description: base64格式图片下载
 * @Date: 2020-02-18 11:25:47
 * @LastEditTime: 2020-02-18 11:33:11
 * @LastEditors: 熊伟
 */

//base64转blob
const base64ToBlob = function(code){
    let parts = code.split(';base64,');
    let contentType = parts[0].split(':')[1];
    let raw = window.atob(parts[1]);
    let rawLength = raw.length;

    let uInt8Array = new Uint8Array(rawLength);

    for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }
    return new Blob([uInt8Array], {type: contentType});
}

const imageDownload = function(fileName, content) {
    if (window.navigator.msSaveOrOpenBlob) {
        // 兼容ie做特殊处理
        var bstr = atob(content.split(',')[1])
        var n = bstr.length
        var u8arr = new Uint8Array(n)
        while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
        }
        var blob = new Blob([u8arr])
        window.navigator.msSaveOrOpenBlob(blob, 'chart-download' + '.' + 'png')
    }else{
        let aLink = document.createElement('a');
        let blob = base64ToBlob(content); //new Blob([content]);

        let evt = document.createEvent("HTMLEvents");
        evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
        aLink.download = fileName;
        aLink.href = URL.createObjectURL(blob);

        // aLink.dispatchEvent(evt);
        aLink.click()
    }
}




export default imageDownload